package com.sunwoda.springbootredis.service.impl;

import com.sunwoda.springbootredis.dao.UserDao;
import com.sunwoda.springbootredis.entity.User;
import com.sunwoda.springbootredis.service.OpsHashService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;

/**
 * @program: springbootredis
 * @description: 操作hash
 * @author: SGR
 * @create: 2021-09-13 11:26
 **/
@Service
@Slf4j
public class OpsHashServiceImpl implements OpsHashService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void opsHash() {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        List<User> list = userDao.queryAll(new User());

        if (CollectionUtils.isEmpty(list)){
            return;
        }

        BoundHashOperations ops = redisTemplate.boundHashOps("Hash");
        list.forEach(one -> {
//            向Hash列表中存值
            ops.put(one.getId().toString(),one.getName());
//            获取值
            Object o = ops.get(one.getId().toString());
            log.info(o.toString());
        });

//        获取hash中所有键
        Set keys = ops.keys();
        log.info("Hash的所有键"+keys);

//        获取hash中所有的值
        List values = ops.values();
        log.info("Hash所有值"+values);

        BoundHashOperations newHash = redisTemplate.boundHashOps("newHash");
        list.forEach(one -> {
            newHash.put(one.getName(),one.getAge());
        });

        List values1 = newHash.values();
        log.info("newHash:"+values1);
//        ops.increment("迪丽热巴",20);
//        log.info("newHash:"+values1);
    }
}
